<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/logo.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          多线程—管程-悲观锁相关内容以及synchronized做的优化 - 宋正兵的博客 | zbsong Blog
        
    </title>

    <link rel="canonical" href="zbsong.top/article/多线程—synchronized/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">

    <link rel="stylesheet" href="/css/donate.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('https://api.dujin.org/bing/1920.php')
            /*post*/
        
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#java" title="java">java</a>
                            
                        </div>
                        <h1>多线程—管程-悲观锁相关内容以及synchronized做的优化</h1>
                        <!-- <h2 class="subheading">悲观锁（阻塞）,synchronized,monitor,mark word</h2> -->
                        <span class="meta">
                            宋正兵 on
                            2021-03-01
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">songzblink</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">主页</a>
                    </li>
					<li>
                        <a href="/archive/">归档</a>
                    </li>
					<li>
                        <a href="/tags/">标签</a>
                    </li>
					<li>
                        <a href="/about/">关于</a>
                    </li>
					<!--
					修改about在前面的问题
                    
                        
                    
                        
                        <li>
                            <a href="/about/">关于</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/archive/">归档</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/tags/">标签</a>
                        </li>
                        
                    
                    -->
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
	// querySelector 获取文档中 id="demo" 的元素
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				
                <p>为了避免临界区的竞态条件发生，产生资源共享问题，可以使用 synchronized【对象锁】来解决问题。</p>
<p>它采用互斥的方式让同一时刻至多只有一个线程能持有【对象锁】，其它线程再想获取这个【对象锁】时就会阻塞住。这样就能保证拥有锁的线程可以安全的执行临界区内的代码，不用担心线程上下文切换。</p>
<h2 id="synchronized">synchronized</h2>
<h3 id="synchronized的使用">synchronized的使用</h3>
<p>语法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span>(对象) &#123;</span><br><span class="line">    <span class="comment">// 临界区</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用法</p>
<p>1）加在方法上的作用就是锁住当前对象 this</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span>(<span class="keyword">this</span>) &#123;</span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>2）加在 static 方法上等同于锁住类对象 xxx.class</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span>(Test.class) &#123;</span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="synchronized的原理">synchronized的原理</h3>
<p>在展开讨论 synchronized 的远离之前，需要先引入<strong>对象头</strong>和<strong>Monitor</strong>两个知识。</p>
<p><strong>对象头</strong></p>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/image.png" alt="image.png"></p>
<p>其中 Mark Word 的结构为</p>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/imagec95e7ded9525212e.png" alt="imagec95e7ded9525212e.png"></p>
<p><strong>Monitor</strong></p>
<p>Monitor 被翻译为<strong>监视器</strong>或<strong>管程</strong></p>
<p>每个 Java 对象都可以关联一个 Monitor 对象，如果使用 synchronized 给对象上锁（重量级）之后，该对象头的 Mark Word 中就被设置指向 Monitor 对象的指针</p>
<p>Monitor 结构如下</p>
<p><img src="https://pic.tyzhang.top/images/2021/02/27/image358d93b916e03413.png" alt="image358d93b916e03413.png"></p>
<hr>
<p>synchronized 给对象上锁流程【重量级锁】</p>
<ul>
<li>刚开始 Monitor 中 Owner 为 null</li>
<li>当 Thread-2 执行 synchronized(obj) 就会将 Monitor 的所有者 Owner 置为 Thread-2，Monitor 中只能有一个 Owner</li>
<li>在 Thread-2 上锁的过程中，如果 Thread-3，Thread-4，Thread-5 也来执行 synchronized(obj)，就会进入 EntryList BLOCKED</li>
<li>Thread-2 执行完同步代码块的内容，然后唤醒 EntryList 中等待的线程来竞争锁</li>
<li>图中 WaitSet 中的 Thread-0，Thread-1 是之前获得过锁，但条件不满足运行而进入 WAITING 状态的线程</li>
</ul>
<blockquote>
<p>BLOCK 和 WAITING 的线程都处于阻塞状态，不占用 CPU 时间片</p>
<p>BLOCK 线程会在 Owner 线程释放锁时唤醒</p>
<p>WAITING 线程会在 Owner 线程调用 notify 或 notifyAll 时唤醒，但唤醒后并不意味着立刻获得锁，仍然需要进入 EntryList 重新竞争</p>
</blockquote>
<p>WaitSet（休息室）：当前获得锁的线程（Owner）是屋子的主人，但是该线程可能因为条件不足（如等待 I\O 获取数据）而无法继续往下运行，这个时候就会调用 wait()，进入 WaitSet ，等待条件好了才能继续运行。</p>
<p>此时它会让出锁，让 EntryList 排队等待的线程来竞争锁；当条件满足了当前获得锁的线程就会调用 notify() 唤醒 WaitSet 休息室中的线程，它就回去重新跟别人一起排队，去竞争锁。</p>
<blockquote>
<p><strong>注意：</strong></p>
<ul>
<li>synchronized 必须是进入同一个对象的 monitor 才有上述的效果</li>
<li>不加  synchronized 的对象不会关联监视器，不遵从以上原则</li>
</ul>
</blockquote>
<h2 id="谈谈锁synchronized优化">谈谈锁——synchronized优化</h2>
<h3 id="流程">流程</h3>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/imagec95e7ded9525212e.png" alt="imagec95e7ded9525212e.png"></p>
<p>一个对象创建时：</p>
<ul>
<li>
<p>如果开启了偏向锁（默认开启），那么对象创建后，Mark Word 值为 <code>0x05</code> 即最后 3 位为 <code>101</code>，这时它的 thread、epoch、age 都为 0</p>
<blockquote>
<p>偏向锁是默认延迟的，不会在程序启动时立即生效，如果想避免延迟，可以添加 VM 参数来禁用延迟 。</p>
</blockquote>
<ul>
<li>
<p>偏向锁的工作愿意：只有第一次使用 CAS 才将线程 ID 设置到对象的 Mark Word 头，之后发现这个线程 ID 是自己的就表示没有竞争，不用重新 CAS</p>
</li>
<li>
<p>偏向锁的失效</p>
<blockquote>
<p>失效后的再加锁加的是轻量级锁</p>
</blockquote>
<ul>
<li>调用对象 hashCode</li>
<li>其它线程使用对象</li>
<li>调用 wait/notify</li>
</ul>
</li>
<li>
<p>没有锁竞争的前提下</p>
<ul>
<li>撤销偏向锁阈值超过 20 次：偏向锁批量重偏向</li>
<li>撤销偏向锁阈值超过 40 次：偏向锁批量撤销</li>
</ul>
</li>
</ul>
</li>
<li>
<p>如果没有开启偏向锁，那么对象创建后，Mark Word 值为 <code>0x01</code> 即最后 3 位为 <code>001</code>，这时它的 hashcode、age 都为 0，第一次用到 hashcode 时才会赋值</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">偏向锁  ----失效后再加锁----&gt; 轻量级锁 ----锁膨胀----&gt; 重量级锁</span><br><span class="line">|- 偏向锁的失效			   |- 锁重入				|- 自旋</span><br><span class="line">|- 偏向锁的批量重偏向		 |- 锁膨胀</span><br><span class="line">|- 偏向锁的批量撤销</span><br></pre></td></tr></table></figure>
<h3 id="轻量级锁">轻量级锁</h3>
<p>轻量级锁的使用场景：如果一个对象虽然有多线程访问，但多线程访问的时间是错开的（也就是<strong>没有竞争</strong>），那么可以使用轻量级锁来优化</p>
<p>轻量级锁对使用者是透明的，即语法仍然是 synchronized</p>
<p>假设有两个方法同步块，利用同一个对象加锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> Object obj = <span class="keyword">new</span> Object();</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块 A</span></span><br><span class="line">        method2();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块 B</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>method1() 中调用了 method2()，method2() 也加了 synchronized，此时发生了<strong>锁重入</strong>，对同一个对象加多重锁。</p>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/image4698f1c89082b449.png" alt="image4698f1c89082b449.png"></p>
<blockquote>
<ol>
<li>栈帧的锁记录使用 CAS 尝试替换对象头的 Mark Word</li>
<li>当前线程内继续加锁，（锁重入）计数器 +1（相应的，解锁 -1）</li>
<li>别的线程来加锁，发现已经存在轻量级锁了，就会转成重量级锁（<strong>锁膨胀</strong>）</li>
</ol>
</blockquote>
<h3 id="锁膨胀">锁膨胀</h3>
<p>如果在尝试加轻量级锁的过程中，CAS 操作无法成功，这时一种情况就是有其它线程为此对象加上了轻量级锁（有竞争），这时需要进行锁膨胀，将轻量级锁变为重量级锁。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> Object obj = <span class="keyword">new</span> Object();</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/imagea4f250948efe762b.png" alt="imagea4f250948efe762b.png"></p>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/image7372f553d60664b0.png" alt="image7372f553d60664b0.png"></p>
<h3 id="自旋">自旋</h3>
<p>重量级锁竞争的时候，还可以使用自旋来进行优化，如果当前线程自旋成功（即这时候持有锁的线程已经退出同步块，释放了锁），这时当前线程就可以避免阻塞。</p>
<ul>
<li>自旋会占用 CPU 时间，单核 CPU 自旋就是浪费时间，多核 CPU 自旋才能发挥优势。</li>
<li>在 Java 6 之后自旋锁是自适应的，比如对象刚刚的一次自旋操作成功过，那么认为这次自选成功的可能性高，就多自旋几次；反之，就少自旋甚至不自旋。</li>
<li>Java 7 之后不能控制是否开启自旋功能</li>
<li>（自旋类似于重复尝试）</li>
</ul>
<p>自旋重试成功的情况</p>
<table>
<thead>
<tr>
<th>线程1（cpu1 上）</th>
<th>对象 Mark</th>
<th>线程2（cpu2 上）</th>
</tr>
</thead>
<tbody>
<tr>
<td>-</td>
<td>10（重量锁）</td>
<td>-</td>
</tr>
<tr>
<td>访问同步块，获取 monitor</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>成功（加锁）</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>访问同步块，获取 monitor</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td><strong>成功（解锁）</strong></td>
<td>01（无锁）</td>
<td>自旋重试</td>
</tr>
<tr>
<td>-</td>
<td>10（重量锁）重量锁指针</td>
<td><strong>成功（加锁）</strong></td>
</tr>
<tr>
<td>-</td>
<td>10（重量锁）重量锁指针</td>
<td><strong>执行同步块</strong></td>
</tr>
<tr>
<td>-</td>
<td>…</td>
<td>…</td>
</tr>
</tbody>
</table>
<p>自旋重试失败的情况</p>
<table>
<thead>
<tr>
<th>线程1（cpu1 上）</th>
<th>对象 Mark</th>
<th>线程2（cpu2 上）</th>
</tr>
</thead>
<tbody>
<tr>
<td>-</td>
<td>10（重量锁）</td>
<td>-</td>
</tr>
<tr>
<td>访问同步块，获取 monitor</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>成功（加锁）</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>-</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>访问同步块，获取 monitor</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td>自旋重试</td>
</tr>
<tr>
<td>执行同步块</td>
<td>10（重量锁）重量锁指针</td>
<td><strong>阻塞</strong></td>
</tr>
<tr>
<td>-</td>
<td>…</td>
<td>…</td>
</tr>
</tbody>
</table>
<h3 id="偏向锁">偏向锁</h3>
<p>轻量级锁在没有竞争时（只有自己这个线程），每次重入仍然需要执行 CAS 操作。</p>
<p>Java 6 中引入了偏向锁来做进一步优化：只有第一次使用 CAS 才将线程 ID 设置到对象的 Mark Word 头，之后发现这个线程 ID 是自己的就表示没有竞争，不用重新 CAS。以后只要不发生竞争，这个对象就归该线程所有。</p>
<p>例如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> Object obj = <span class="keyword">new</span> Object();</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块A</span></span><br><span class="line">        method2();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块B</span></span><br><span class="line">        method3();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">method3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        <span class="comment">// 同步块C</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://pic.tyzhang.top/images/2021/02/28/image664fd7f7c01e45a2.png" alt="image664fd7f7c01e45a2.png"></p>
<p>一个对象创建时：</p>
<ul>
<li>如果开启了偏向锁（默认开启），那么对象创建后，Mark Word 值为 <code>0x05</code> 即最后 3 位为 <code>101</code>，这时它的 thread、epoch、age 都为 0</li>
<li>偏向锁是默认延迟的，不会在程序启动时立即生效，如果想避免延迟，可以添加 VM 参数来禁用延迟</li>
<li>如果没有开启偏向锁，那么对象创建后，Mark Word 值为 <code>0x01</code> 即最后 3 位为 <code>001</code>，这时它的 hashcode、age 都为 0，第一次用到 hashcode 时才会赋值</li>
</ul>
<h3 id="偏向锁的失效">偏向锁的失效</h3>
<h4 id="1撤销-调用对象-hashcode">1）撤销-调用对象 hashCode</h4>
<p>偏向锁对象的 MarkWord 中存储的是线程 ID，如果调用了锁对象的 hashCode 会导致偏向锁撤销</p>
<ul>
<li>轻量级锁会在锁记录中记录 hashCode（存放在栈帧的锁记录中）</li>
<li>重量级锁会在 Monitor 中记录 hashCode</li>
</ul>
<h4 id="2撤销-其它线程使用对象">2）撤销-其它线程使用对象</h4>
<p>当有其它线程使用偏向锁对象时，会将偏向锁升级为轻量级锁</p>
<h4 id="3撤销-调用-waitnotify">3）撤销-调用 wait/notify</h4>
<h3 id="偏向锁批量重偏向">偏向锁批量重偏向</h3>
<p>如果对象虽然被多个线程访问，但<strong>没有竞争</strong>，这时偏向了线程 t1 的对象仍然有机会重新偏向线程 t2，重偏向会重置对象的 Thread ID。</p>
<p>当撤销偏向锁阈值超过 20 次后，jvm 会在给这些对象加锁时重新偏向至加锁线程。</p>
<h3 id="偏向锁批量撤销">偏向锁批量撤销</h3>
<p>当撤销偏向锁阈值超过 40 次后，jvm 会将整个类的所有对象都变为不可偏向的，新建的对象也是不可偏向的。</p>
<h3 id="锁消除">锁消除</h3>
<p>如下代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">b</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Object obj = <span class="keyword">new</span> Object();</span><br><span class="line">    <span class="keyword">synchronized</span>(obj) &#123;</span><br><span class="line">        x++;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>JIT 即时编译器会对 Java 字节码进一步的优化，上述代码中，局部变量 obj 不会逃离方法，不可能被共享，所以对加锁没有任何意义。于是 JIT 编译器优化，将锁去掉了。</p>
<h3 id="其他优化">其他优化</h3>
<ol>
<li>
<p>减少上锁时间，同步代码块尽量短</p>
</li>
<li>
<p>减少锁的粒度</p>
<p>将一个锁拆分为多个锁提高并发度，例如</p>
<ul>
<li>ConcurrentHashMap</li>
<li>LongAdder 分为 base 和 cells 两部分。没有并发争用的时候或者是 cells 数组正在初始化时候，会使用 CAS 来累加值到 base，有并发争用，会初始化 cells 数组，数组有多少个 cell，就允许有多少线程并行修改，最后将数组中每个 cell 累加，再加上 base 就是最终的值。</li>
<li>LinkedBlockingQueue 入队和出队使用不同的锁，相对于 LinkedBlockingQueueArray 只有一个锁效率要高。</li>
</ul>
</li>
<li>
<p>锁粗化</p>
<p>多次循环进入同步块不如同步块内多次循环 另外 JVM 可能会做如下优化，把多次 append 的加锁操作粗化为一次(因为都是对同一个对象加锁，没必要重入多次)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">new StringBuffer().append(&quot;a&quot;).append(&quot;b&quot;).append(&quot;c&quot;);</span><br></pre></td></tr></table></figure>
</li>
<li>
<p>锁消除</p>
<p>JVM 会进行代码的逃逸分析，例如某个加锁对象是方法内局部变量，不会被其它线程所访问到，这时候就会被即时编译器忽略掉所有同步操作。</p>
</li>
<li>
<p>读写分离</p>
<ul>
<li>CopyOnWriteArrayList</li>
<li>ConyOnWriteSe</li>
</ul>
</li>
</ol>

                
                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/article/阅读记录/" data-toggle="tooltip" data-placement="top" title="阅读记录">&larr; 上一篇</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/article/Numpy进行向量矩阵计算/" data-toggle="tooltip" data-placement="top" title="Numpy的基础——向量计算矩阵计算">下一篇 &rarr;</a>
                        </li>
                    
                </ul>

                <br>

                <!--打赏-->
                
                <!--打赏-->

                <br>
                <!--分享-->
                
                <!--分享-->
                <br>                       
                
                <!-- require APlayer -->
                
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

  
    <style>
      span.toc-nav-number{
        display: none
      }
    </style>
  
    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#synchronized"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">synchronized</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#synchronized的使用"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">synchronized&#x7684;&#x4F7F;&#x7528;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#synchronized的原理"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">synchronized&#x7684;&#x539F;&#x7406;</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#谈谈锁synchronized优化"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">&#x8C08;&#x8C08;&#x9501;&#x2014;&#x2014;synchronized&#x4F18;&#x5316;</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#流程"><span class="toc-nav-number">2.1.</span> <span class="toc-nav-text">&#x6D41;&#x7A0B;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#轻量级锁"><span class="toc-nav-number">2.2.</span> <span class="toc-nav-text">&#x8F7B;&#x91CF;&#x7EA7;&#x9501;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#锁膨胀"><span class="toc-nav-number">2.3.</span> <span class="toc-nav-text">&#x9501;&#x81A8;&#x80C0;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#自旋"><span class="toc-nav-number">2.4.</span> <span class="toc-nav-text">&#x81EA;&#x65CB;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#偏向锁"><span class="toc-nav-number">2.5.</span> <span class="toc-nav-text">&#x504F;&#x5411;&#x9501;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#偏向锁的失效"><span class="toc-nav-number">2.6.</span> <span class="toc-nav-text">&#x504F;&#x5411;&#x9501;&#x7684;&#x5931;&#x6548;</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1撤销-调用对象-hashcode"><span class="toc-nav-number">2.6.1.</span> <span class="toc-nav-text">1&#xFF09;&#x64A4;&#x9500;-&#x8C03;&#x7528;&#x5BF9;&#x8C61; hashCode</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2撤销-其它线程使用对象"><span class="toc-nav-number">2.6.2.</span> <span class="toc-nav-text">2&#xFF09;&#x64A4;&#x9500;-&#x5176;&#x5B83;&#x7EBF;&#x7A0B;&#x4F7F;&#x7528;&#x5BF9;&#x8C61;</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3撤销-调用-waitnotify"><span class="toc-nav-number">2.6.3.</span> <span class="toc-nav-text">3&#xFF09;&#x64A4;&#x9500;-&#x8C03;&#x7528; wait/notify</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#偏向锁批量重偏向"><span class="toc-nav-number">2.7.</span> <span class="toc-nav-text">&#x504F;&#x5411;&#x9501;&#x6279;&#x91CF;&#x91CD;&#x504F;&#x5411;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#偏向锁批量撤销"><span class="toc-nav-number">2.8.</span> <span class="toc-nav-text">&#x504F;&#x5411;&#x9501;&#x6279;&#x91CF;&#x64A4;&#x9500;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#锁消除"><span class="toc-nav-number">2.9.</span> <span class="toc-nav-text">&#x9501;&#x6D88;&#x9664;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#其他优化"><span class="toc-nav-number">2.10.</span> <span class="toc-nav-text">&#x5176;&#x4ED6;&#x4F18;&#x5316;</span></a></li></ol></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">标签</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#java" title="java">java</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
				<!--
                
                <hr>
                <h5>朋友们</h5>
                <ul class="list-inline">

                    
                        <li><a href="https://tyzhang.top/" target="_blank">ztygalaxy</a></li>
                    
                        <li><a href="http://www.yctang.club/" target="_blank">yctang</a></li>
                    
                        <li><a href="https://dolnw.github.io" target="_blank">JCWang</a></li>
                    
                </ul>
                
				-->
            </div>
        </div>
    </div>
</article>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: ''
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>


<!-- chrome Firefox 中文锚点定位失效-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<!-- smooth scroll behavior polyfill  -->
<script type="text/javascript" src="/js/smoothscroll.js"></script>
<script>
        $('#toc').on('click','a',function(a){
            // var isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;
            // console.log(window.navigator.userAgent,isChrome)
                // if(isChrome) {
                    // console.log(a.currentTarget.outerHTML);
                    // console.log($(a.currentTarget).attr("href"));
                    //跳转到指定锚点
                    // document.getElementById(a.target.innerText.toLowerCase()).scrollIntoView(true);
                    document.getElementById($(a.currentTarget).attr("href").replace("#","")).scrollIntoView({behavior: 'smooth' });
                // }
        })  
</script>


    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                
				
                

                

                
                    <li>
                        <a target="_blank"  href="https://github.com/songzblink">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; 宋正兵 2021 
                    <br>
                    Theme by <a href="http://www.huweihuang.com">Huwei Huang</a>
                    re-Ported by <a href="https://github.com/ztygalaxy">ztygalaxy</a>
					
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("zbsong.top/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="zbsong.top/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<!--
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</body>

</html>
